<template>
  <div class="nav-login">
    <van-nav-bar class="top-nav" title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        required
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确手机号'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        required
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '请输入正确验证码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isDisabled"
          loading-text="加载中。。。"
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 抽取接口
import { userLogin } from '../../api/login.js'
import { saveToken } from '../../utils/token'
export default {
  name: 'login',
  data () {
    return {
      mobile: '14788888888',
      code: '246810',
      isDisabled: false,
      isLoading: false
    }
  },

  methods: {
    // submit点击事件

    onSubmit (values) {
      // 点击之后立马禁用按钮，并显示加载动画
      this.isDisabled = true
      this.isLoading = true
      // console.log('submit', values)
      // 发送请求
      userLogin(values)
        .then(res => {
          // console.log(res)
          // 储存令牌
          saveToken(res.data.data)
          // 删除令牌
          // removeToken()
          // 取出令牌
          // console.log(getToken())

          // 获取数据立马开启按钮并隐藏加载动画
          this.isDisabled = false
          this.isLoading = false
          // 直接提示
          // this.$toast('提交完')
          // 成功提示
          this.$toast.success('登入成功')
          if (this.$route.query.back) {
            // 如果有值就跳转里面值的地址
            this.$router.push({ path: this.$route.query.back })
          } else {
            // 如果没有则跳首页
            this.$router.push({ path: '/home' })
          }
          // 自定义提示
          // this.$toast({
          //   message: '登录成功',
          //   position: 'top'
          // })
        })
        .catch(err => {
          console.log(err)
          // 获取数据立马开启按钮并隐藏加载动画
          this.isDisabled = false
          this.isLoading = false
          // 错误提示
          this.$toast.fail('登入失败')
        })
    }
  }
}
</script>

<style lang="less">
.nav-login {
  .top-nav {
    background-color: #137dff;
    .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>
